package com.coalmine.api.filter;

import cn.hutool.json.JSONObject;
import com.coalmine.api.service.impl.ApiIpRulesServiceImpl;
import com.coalmine.api.util.IPUtil;
import com.coalmine.common.constant.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 防火墙ip过滤器
 * @author 尚郑
 *
 */
@Slf4j
@Component
public class ApiIPFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException {
        JSONObject json = new JSONObject();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String originIp = IPUtil.getOriginIp(request);

        String method = request.getMethod();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // 跨域设置
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization");//这里很重要，要不然js header不能跨域携带  Authorization属性
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");

        try {

            //js跨域的预检请求，不经过处理逻辑。开发模式下，前端启动，访问8521的页面进行请求测试会跨域
            if (method.equals("OPTIONS")) {
                response.setStatus(HttpServletResponse.SC_OK);
                return;
            }
            boolean checkIP = ApiIpRulesServiceImpl.checkIP(originIp);
            if (!checkIP) {
                json.put("code", HttpStatus.UNAUTHORIZED);
                json.put("msg", "IP (" + originIp + ")无权访问,请联系管理员！！！");
                setResponse(response,json.toString());
                return;
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            json.put("code", HttpStatus.ERROR);
            json.put("msg", "系统异常....");
            setResponse(response,json.toString());
            return;
        }

    }

    @Override
    public void destroy() {

    }

    public void setResponse(HttpServletResponse response, String msg) {
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(msg);
        } catch (IOException e) {
            log.error("响应失败！");
        } finally {
            pw.flush();
            pw.close();
        }
    }
}